import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/cache/language_cache.dart';
import 'package:wu_you/data/cache/language_name_cache.dart';
import 'package:wu_you/data/cache/username_password_cache.dart';
import 'package:wu_you/data/db/dao/login_history_dao.dart';
import 'package:wu_you/data/db/dao/transfer_user_dao.dart';
import 'package:wu_you/http/http.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/main.dart';
import 'package:wu_you/model/home/home_model.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/home_bloc.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/utils/login_util.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:package_info/package_info.dart';

class SettingPage extends StatefulWidget{
  @override
  SettingPageState createState() => SettingPageState();
}
class SettingPageState extends State<SettingPage>{
  var message;

  String phone;
  String _version = '';
  @override
  void initState() {
    super.initState();
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        _version = packageInfo.version;
      });
    });
    UsernamePasswordCache cache = UsernamePasswordCache();
    cache.getArray().then((value) {
      phone = value[0];
    });
  }
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("${message['setting']}"),
      ),
      body: Column(
        children: [
          ListTile(
            leading: Image.asset(Utils.getImgPath('language_set'),width: 28,height: 28,),
            title: Text("当前版本",style: TextStyle(fontSize: 15,color: AppColors.textColor),),
            trailing: Icon(Icons.arrow_forward_ios_outlined,size: 18,color: AppColors.textHintColor,),
            onTap: (){
              ToastUtils.show("版本:${_version}", context);
            },
          ),
          Divider(thickness: 1,),
          ListTile(
            leading: Image.asset(Utils.getImgPath('clear_cache'),width: 26,height: 26,),
            title: Text("${message['clearCache']}",style: TextStyle(fontSize: 15,color: AppColors.textColor),),
            trailing: Icon(Icons.arrow_forward_ios_outlined,size: 18,color: AppColors.textHintColor,),
            onTap: (){
              showCupertinoDialog(
                  context: context,
                  builder: (context) {
                    return CupertinoAlertDialog(
                      title: Text('${message['trad24']}'),
                      content: Text('${message['clearCacheNot']}'),
                      actions: <Widget>[
                        CupertinoDialogAction(child: Text('${message['address14']}'),onPressed: (){
                          Navigator.pop(context);
                        },),
                        CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: () async{
                          await TransferUserDao().deleteAll(phone);
                          await LoginHistoryDao().deleteAll();
                          ToastUtils.show("${message['Success']}", context);
                          Navigator.of(context).pop();
                        },),
                      ],
                    );
                  });
            },
          ),
          Divider(thickness: 1,),

          ListTile(
            leading: Image.asset(Utils.getImgPath('login_out'),width: 30,height: 30,),
            title: Text("${message['logOut']}",style: TextStyle(fontSize: 15,color: AppColors.textColor),),
            trailing: Icon(Icons.arrow_forward_ios_outlined,size: 18,color: AppColors.textHintColor,),
            onTap: (){
              showCupertinoDialog(
                  context: context,
                  builder: (context) {
                    return CupertinoAlertDialog(
                      title: Text('${message['trad24']}'),
                      content: Text('${message['logOut']}？'),
                      actions: <Widget>[
                        CupertinoDialogAction(child: Text('${message['address14']}'),onPressed: (){
                          Navigator.pop(context);
                        },),
                        CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: (){
                          LoginUtil.logout(context: context);
                          Navigator.of(context).pop();
                        },),
                      ],
                    );
                  });
            },
          ),
          Divider(thickness: 1,),
        ],
      ),
    );
  }
}


class SelectLanguagePage extends StatefulWidget{
  @override
  SelectLanguagePageState createState() => SelectLanguagePageState();
}
class SelectLanguagePageState extends State<SelectLanguagePage>{
  var message;

  String lv = "1";


  List<LanguageModel> languageList = [LanguageModel(id: "1",language: "中文 Chinese"),LanguageModel(id: "2",language: "英文 English")];
  @override
  void initState() {
    super.initState();
    LanguageCache().get().then((v){
      setState(() {
        lv = v;
      });
    });
  }
  BuildContext ctx;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("${message['language']}"),
      ),
      backgroundColor: Colors.white,
      body: ListView.builder(
        itemBuilder: (context,index){
          LanguageModel lm = languageList[index];
          return  Container(
              height: 55,
              width: double.infinity,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(18)),
                  color:lv == lm.id ? AppColors.primaryColor : HexColor("#F6F6F6")
              ),
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 30),
              margin: EdgeInsets.only(left: 15,right: 12,top: 15),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    child: Offstage(
                      offstage: lv == lm.id ? false : true,
                      child: Image.asset(Utils.getImgPath('language_check'),width: 25,height: 25,),
                    ),
                    width: 25,
                    height: 55,
                  ),
                  SizedBox(width: 12,),
                  Text("${lm.language}",style: TextStyle(fontSize: 17,fontWeight: FontWeight.bold,color: lv == lm.id ? Colors.white : Colors.black),),
                ],
              )
          ).addGesture(() async{
            //切换语言
            ///保存语言id
            lv = lm.id;
            await LanguageCache().save(lm.id);
            await LanguageNameCache().save(lm.language);
            Http().language = lm.id;
            ///不为中国都为英文
            var currentLocale = Localizations.localeOf(context);
            var newLocale = lm.id == "1" ? const Locale('zh', '') : const Locale('en', '');
            MyApp.setLocale(context, newLocale);

            setState(() {

            });
          });
        },
        itemCount: languageList.length,
      )
    );
  }
}